package com.xoa.service.attend;


import com.xoa.dao.attend.AttendEvectionMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.attend.AttendEvection;
import com.xoa.model.attend.AttendEvectionFlowRunPrcs;
import com.xoa.model.attend.AttendFlowRunPrcs;
import com.xoa.model.attend.AttendOut;
import com.xoa.model.common.SysCode;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFast;
import com.xoa.model.workflow.FlowRun;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.attend.wrapper.AttendSetWrappers;
import com.xoa.service.work.WorkService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateCompute;
import com.xoa.util.DateFormat;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/7/5.
 */
@Service
public class AttendEvectionService {
    @Autowired
    private AttendEvectionMapper attendEvectionMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;




    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-7-14 下午14:45:00
     * 方法介绍:   查询出差登记
     */
    public ToJson<AttendEvectionFlowRunPrcs> queryAllAttendEvection(Integer page, Integer pageSize,
                                                         Boolean useFlag,HttpServletRequest  request,String FlowAllow){
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("userId", users.getUserId());
        objectMap.put("flowAllow",FlowAllow);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ToJson<AttendEvectionFlowRunPrcs> json = new ToJson<AttendEvectionFlowRunPrcs>(1, "error");
        try{
            List<AttendEvectionFlowRunPrcs> attendEvectionList=attendEvectionMapper.queryAllAttendEvection(objectMap);
            for (AttendEvection attendEvection:attendEvectionList){
                if(!StringUtils.checkNull(attendEvection.getUserId())) {
                    if(usersMapper.findUsersByuserId(attendEvection.getUserId())!=null){
                        attendEvection.setUserName(usersMapper.findUsersByuserId(attendEvection.getUserId()).getUserName());
                    }
                   if(usersMapper.findUsersByuserId(attendEvection.getUserId())!=null){
                        if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendEvection.getUserId()).getDeptId())!=null){
                            attendEvection.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendEvection.getUserId()).getDeptId()));
                        }
                   }
                }

                if(!StringUtils.checkNull(attendEvection.getAgent())){
                    if(usersMapper.findUsersByuserId(attendEvection.getAgent())!=null){
                        attendEvection.setAgent(usersMapper.findUsersByuserId(attendEvection.getAgent()).getUserName());
                    }
                }
                if(!StringUtils.checkNull(attendEvection.getStatus())){
                    int status=Integer.valueOf(attendEvection.getStatus());
                    switch (status){
                        case 1:
                            attendEvection.setStatus("未确认");
                            break;
                        case 2:
                            attendEvection.setStatus("已确认");
                            break;
                    }
                }
                if(!StringUtils.checkNull(attendEvection.getAllow())){
                    int allow=Integer.valueOf(attendEvection.getAllow());
                    switch (allow){
                        case 0:
                            attendEvection.setAllow("待审批");
                            break;
                        case 1:
                            attendEvection.setAllow("已批准");
                            break;
                        case 2:
                            attendEvection.setAllow("未批准");
                            break;
                    }
                }


                if(attendEvection.getEvectionDate1()!=null&&attendEvection.getEvectionDate2()!=null){
                    attendEvection.setBeginDate(DateFormat.getStrDate(attendEvection.getEvectionDate1()));
                    attendEvection.setEndDate(DateFormat.getStrDate(attendEvection.getEvectionDate2()));
                    long begin= DateFormat.getTime(sdf.format(attendEvection.getEvectionDate1()));
                    long end=DateFormat.getTime(sdf.format(attendEvection.getEvectionDate2()));
                    attendEvection.setEvectionTime(DateFormat.returnTime((int)(end-begin)));
                }else {
                    attendEvection.setBeginDate("");
                    attendEvection.setEndDate("");
                    attendEvection.setEvectionTime("");
                }
               FlowRunPrcs flowRunPrcs= flowRunPrcsMapper.queryByRunId(attendEvection.getRunId());
                if(flowRunPrcs!=null){
                    attendEvection.setFlowPrcs(flowRunPrcs.getFlowPrcs().toString());
                    attendEvection.setPrcsId(flowRunPrcs.getPrcsId().toString());
                }else {
                    attendEvection.setFlowPrcs("");
                    attendEvection.setPrcsId("");
                }
                FlowRun flowRun=flowRunMapper.find(attendEvection.getRunId());
                if(flowRun!=null){
                    attendEvection.setRunId(flowRun.getRunId());
                }



            }
            json.setObj(attendEvectionList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setTotleNum(pageParams.getTotal());
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("AttendService queryAllAttendEvection:"+e);
        }
        return  json;
    }
    public BaseWrapper addAttendEvection(String createDate, HttpServletRequest request){
        BaseWrapper baseWrapper=new BaseWrapper();
        AttendEvection  attendEvection=new AttendEvection();
        String  sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        List<SysCode>  SysCode= sysCodeMapper.getSysCode("KQQJTYPE");
        for(SysCode sysCode:SysCode){
            if(sysCode.getCodeName().equals("出差申请")){
                ToJson<FlowFast> flowFastToJson=  wfeFlowRunInfo.workFastAdd(users, Integer.parseInt(sysCode.getCodeNo()) ,1,"1","",request,sqlType,"",null);
                if(flowFastToJson.isFlag()){
                    FlowFast flowFast=(FlowFast)flowFastToJson.getObject();
                    attendEvection.setUserId(users.getUserId());
                    attendEvection.setRegisterIp(IpAddr.getIpAddress(request));
                    attendEvection.setRecordTime(DateFormat.getDate(createDate));
                    attendEvection.setRunId(flowFast.getFlowRun().getRunId());
                    attendEvection.setStatus("1");
                    attendEvection.setTableName("attend_evection");
                    attendEvection.setAllow("0");
                    int amount=attendEvectionMapper.insertSelective(attendEvection);
                    if(amount>0){
                        attendEvection.setFlowId(flowFast.getFlowTypeModel().getFlowId().toString());
                        attendEvection.setFlowName(flowFast.getFlowTypeModel().getFlowName());
                        baseWrapper.setFlag(true);
                        baseWrapper.setStatus(true);
                        baseWrapper.setData(attendEvection);
                        baseWrapper.setMsg("更新成功");
                    }
                }
            }

        }
        return  baseWrapper;

    }

    public BaseWrappers backlogAttendList(HttpServletRequest request, String num, Integer page, Integer pageSize,
                                          Boolean useFlag){
        BaseWrappers wrappers =new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users =SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        if(StringUtils.checkNull(users.getUserId())){
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        Map<String,Object> map=new HashMap<String,Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        map.put("userId", users.getUserId());
        wrappers.setTotal(pageParams.getTotal());
        if("1".equals(num)){
            List<AttendEvectionFlowRunPrcs> attendFlowRunPrcs=attendEvectionMapper.backlogAttendEvection(map);
            for(AttendEvectionFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){

                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    attendFlowRunPrcs1.setUserName(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getUserName());
                }
                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }
                if(attendFlowRunPrcs1.getEvectionDate1()!=null&&attendFlowRunPrcs1.getEvectionDate2()!=null){
                    attendFlowRunPrcs1.setBeginDate(DateFormat.getStrDate(attendFlowRunPrcs1.getEvectionDate1()));
                    attendFlowRunPrcs1.setEndDate(DateFormat.getStrDate(attendFlowRunPrcs1.getEvectionDate2()));

                }else {
                    attendFlowRunPrcs1.setBeginDate("");
                    attendFlowRunPrcs1.setEndDate("");
                    attendFlowRunPrcs1.setEvectionTime("");
                }
                attendFlowRunPrcs1.setTableName("attend_evection");

            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }else if("2".equals(num)) {
            List<AttendEvectionFlowRunPrcs> attendFlowRunPrcs=attendEvectionMapper.haveDoneAttendEvection(map);
            for(AttendEvectionFlowRunPrcs attendFlowRunPrcs1:attendFlowRunPrcs){
                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    attendFlowRunPrcs1.setUserName(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getUserName());
                }
                if(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId())!=null){
                    if(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId())!=null){
                        attendFlowRunPrcs1.setDeptName(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(attendFlowRunPrcs1.getUserId()).getDeptId()));
                    }
                }
                if(attendFlowRunPrcs1.getEvectionDate1()!=null&&attendFlowRunPrcs1.getEvectionDate2()!=null){
                    attendFlowRunPrcs1.setBeginDate(DateFormat.getStrDate(attendFlowRunPrcs1.getEvectionDate1()));
                    attendFlowRunPrcs1.setEndDate(DateFormat.getStrDate(attendFlowRunPrcs1.getEvectionDate2()));

                }else {
                    attendFlowRunPrcs1.setBeginDate("");
                    attendFlowRunPrcs1.setEndDate("");
                    attendFlowRunPrcs1.setEvectionTime("");
                }
                attendFlowRunPrcs1.setTableName("attend_evection");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(attendFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }

        return  wrappers;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-11-21  下午5:50:17
     * 方法介绍：查询登录人一段时间内的出差状况
     * 参数说明：
     */
    public ToJson<AttendEvection> selectAttendEvectionByUserId(String beginDate, String endDate,HttpServletRequest req){
        ToJson<AttendEvection> json = new ToJson<AttendEvection>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
            String userId = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(),redisSessionId).getUserId();
            List<Date> dates = DateCompute.getBetweenDates(DateFormat.DateToStr(beginDate), DateFormat.DateToStr(endDate));
            List<AttendEvection> attendEvectionList = attendEvectionMapper.selectAttendEvectionByUserId(userId);
            List<AttendEvection> newAttendEvectionList = new ArrayList<AttendEvection>();
            if(attendEvectionList.size() > 0){
                for (AttendEvection attendEvection : attendEvectionList){
                    for (Date nowDate : dates){
                        String aTime = DateFormat.getDatestr(attendEvection.getRecordTime()).substring(0,10);
                        String nTime = DateFormat.getDatestr(nowDate);
                        if(aTime.equals(nTime)){
                            newAttendEvectionList.add(attendEvection);

                        }
                    }
                }
                json.setObj(newAttendEvectionList);
                json.setFlag(0);
                json.setMsg("ok");
            }else {
                json.setMsg("err");
                json.setFlag(1);
            }

        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }

        return json;
    }



}
